class ThoughtsController < ApplicationController
  before_filter :authenticate, :except => [:index,:show]
  helper :thoughts

  # GET /thoughts
  # GET /thoughts.xml
  def index
    @questions = Thought.paginate :per_page => 10, :page => params[:page],
      :conditions => ['parent_id IS NULL']

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @thoughts }
    end
  end

  # GET /thoughts/1
  # GET /thoughts/1.xml
  def show
    @thought = Thought.find(params[:id])
    @question = @thought.root
    @responses = @question.responses

    #increase view_count
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @question }
    end
  end

  # GET /thoughts/new
  # GET /thoughts/new.xml
  def new
    @question = if params[:parent_id]
      Thought.find(params[:parent_id])
    else
      Thought.new
    end

    @thought = Thought.new(:parent_id => @question.id)
	     
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @thought }
    end
  end

  # GET /thoughts/1/edit
  def edit
    @thought = Thought.find(params[:id])
  end

  # POST /thoughts
  # POST /thoughts.xml
  def create
    @thought = Thought.new(params[:thought])

    respond_to do |format|
      if @thought.save
        flash[:notice] = 'Thought was successfully created.'
        format.html { redirect_to(@thought) }
        format.xml  { render :xml => @thought, :status => :created, :location => @thought }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @thought.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /thoughts/1
  # PUT /thoughts/1.xml
  def update
    @thought = Thought.find(params[:id])

    respond_to do |format|
      if @thought.update_attributes(params[:thought])
        flash[:notice] = 'Thought was successfully updated.'
        format.html { redirect_to(@thought) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @thought.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /thoughts/1
  # DELETE /thoughts/1.xml
  def destroy
    @thought = Thought.find(params[:id])
    @thought.destroy

    respond_to do |format|
      format.html { redirect_to(thoughts_url) }
      format.xml  { head :ok }
    end
  end

  def vote
    @thought = Thought.find(params[:id])
    @vote_value = params[:vote_value].to_i

    return false if @thought.nil? or not [-1,0,1].include?(@vote_value)

    @vote = if params[:vote_value] == 0
      current_user.recant_vote_for(@thought.id)
      nil
    else
      current_user.vote_on(@thought.id, params[:vote_value])
    end
    current_user.save
    
    respond_to {|format| format.js }
  end
end
